<?php

if( !defined( 'MEDIAWIKI' ) )
die(-1);


#install extension hook
//$wgHooks['CategoryPageView'][] = "wfCategoryCache";

function wfGetFreeBaseInfo(){
  return true;
}

function getArtistInfo($query){
  global $wgDBprefix, $wgOut, $wgMemc, $wgTitle, $wgParser;
  $queryUrl = wfUrlencode($query);
  $queryHtml = htmlspecialchars($query, ENT_QUOTES); 
  $queryFB = strtolower(str_replace('+', '_', $queryUrl)); 
  $wiki = ss_getArticleRawText("Artist:".$query);
  if( $wiki == null){//check if wiki page exists about this artist
        
        $query_freebase = $wgMemc->get("query_freebase$queryUrl");
        if ($query_freebase==null || !$query_freebase) {
            $query_freebase = file_get_contents('http://www.freebase.com/api/service/search?query=/music/'.$queryFB);
            $query_freebase = json_decode($query_freebase);
            $wgMemc->set("query_freebase$queryUrl", $query_freebase,  86400); //expires in one day
          
            if (!is_null($query_freebase->result[0]->article->id)){
            	$query_article = file_get_contents('http://www.freebase.com/api/trans/raw'.(string)$query_freebase->result[0]->article->id);
            	$wgMemc->set("query_article$queryUrl", $query_article,  86400); //expires in one day
            } else {
	    }
        } else {
            $query_article = $wgMemc->get("query_article$queryUrl");
        }
     
	$out .= "<p style='display:block; float:left'>"; 
      if (!is_null($query_freebase->result[0]->image->id)){ //if image exists
        $out .= '<img style="float:left;margin:3px" src= "http://img.freebase.com/api/trans/image_thumb/'.(string)$query_freebase->result[0]->image->id.'" />';
      }
      
      $out .= "<h3><a title='$queryHtml' href='/music/$queryUrl'>$queryHtml</a></h3><br>";
      
      if (!is_null($query_freebase->result[0]->article)){
        if (!is_null($query_freebase->result[0]->article->id)){ //if article exists
          $out .= truncate(substr($query_article, 3), 500, "...", true);
        }
      
        $out .= '<div class="freebase-attribution" style="clear:both; font-size: x-small;  height: 10px; "> Source:
        <a href="http://www.freebase.com/view/en/'.$queryFB.'">'.$queryHtml.'</a> on
        <a href="http://www.freebase.com/">Freebase</a>, licensed under
        <a href="http://creativecommons.org/licenses/by/2.5/">CC-BY</a> </div>';
      } else {
 	$out .= wfMsg( 'create_entry' );
      }
      
  } else { //paint the page wiki 
    $out .= "<h3><a title='$queryHtml' href='/music/$queryUrl'>$queryHtml</a></h3>";
    $popts = $wgOut->parserOptions();
    $out .= truncate($wgParser->parse($wiki, $wgTitle, $popts)->getText(), 500, "...", true);
  }
  
  return $out;
}
